package cn.com.dashihui.api.rabbitmq;

import java.io.IOException;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.DefaultConsumer;
import com.rabbitmq.client.Envelope;

import cn.com.dashihui.api.Quartz.GiveTask;
import cn.com.dashihui.api.common.RabbitMQCode;
import cn.com.dashihui.api.dao.Goods;

import com.jfinal.plugin.activerecord.Db;
import com.rabbitmq.client.AMQP.BasicProperties;

public class MsgRecive {
	
	public static void reciveUp(GiveTask task){
		Connection conn = null;
		Channel channel = null;
		try {
			conn = MQFactory.getConnection();
			channel = conn.createChannel();
			
			/*
			 * 声明队列
			 * 
			 * 队列名称
			 * 队列是否持久化
			 * 此连接的独占队列
			 * 自动删除队列
			 * 队列其他配置
			 */
			channel.queueDeclare(RabbitMQCode.Code.QUEUE_UP, true, false, false, null);
			channel.queueDeclare(RabbitMQCode.Code.QUEUE_DOWN, true, false, false, null);
			/*
			 * 绑定队列
			 * 队列名称
			 * 交换机名称
			 * 路由键
			 */
			channel.queueBind(RabbitMQCode.Code.QUEUE_UP, RabbitMQCode.Code.EXCHANGENAME, RabbitMQCode.Code.KEY_UP);
			channel.queueBind(RabbitMQCode.Code.QUEUE_DOWN, RabbitMQCode.Code.EXCHANGENAME, RabbitMQCode.Code.KEY_DOWN);
			
			channel.basicConsume(RabbitMQCode.Code.QUEUE_UP, true, new DefaultConsumer(channel){
				@Override
				public void handleDelivery(String consumerTag, Envelope envelope, BasicProperties properties,
						byte[] body) throws IOException {
					String string = new String(body,"UTF-8");
					System.out.println(string);
					task.addTask(Goods.me().findById(string));
				}
			});
			//让程序一直等待，表示一直监听队列1
			System.in.read();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	
	public static void reciveDown(GiveTask task){
		Connection conn = null;
		Channel channel = null;
		
		try {
			conn = MQFactory.getConnection();
			channel = conn.createChannel();
			/*
			 * 声明队列
			 * 
			 * 队列名称
			 * 队列是否持久化
			 * 此连接的独占队列
			 * 自动删除队列
			 * 队列其他配置
			 */
			channel.queueDeclare(RabbitMQCode.Code.QUEUE_UP, true, false, false, null);
			channel.queueDeclare(RabbitMQCode.Code.QUEUE_DOWN, true, false, false, null);
			/*
			 * 绑定队列
			 * 队列名称
			 * 交换机名称
			 * 路由键
			 */
			channel.queueBind(RabbitMQCode.Code.QUEUE_UP, RabbitMQCode.Code.EXCHANGENAME, RabbitMQCode.Code.KEY_UP);
			channel.queueBind(RabbitMQCode.Code.QUEUE_DOWN, RabbitMQCode.Code.EXCHANGENAME, RabbitMQCode.Code.KEY_DOWN);
			channel.basicConsume(RabbitMQCode.Code.QUEUE_DOWN, true, new DefaultConsumer(channel){
				@Override
				public void handleDelivery(String consumerTag, Envelope envelope, BasicProperties properties,
						byte[] body) throws IOException {
					String string = new String(body,"UTF-8");
					System.out.println(string);
					task.removeTesk(Integer.parseInt(string));
				}
			});
			//让程序一直等待，表示一直监听队列1
			System.in.read();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
}
